package com.gexiaobao.pigeon.ui.fragment.mall

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.flowlayout.FlowLayout
import com.gexiaobao.flowlayout.TagAdapter
import com.gexiaobao.flowlayout.TagFlowLayout
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.model.bean.GoodsSkuResponse
import com.gexiaobao.pigeon.app.model.param.AddShoppingCarParam
import com.gexiaobao.pigeon.app.model.param.CancelCollectParam
import com.gexiaobao.pigeon.app.util.ImageLoaderManager
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentCollectGoodsListBinding
import com.gexiaobao.pigeon.ui.adapter.CollectGoodsListAdapter
import com.gexiaobao.pigeon.ui.mall.MallViewModel
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.kingja.loadsir.core.LoadService
import com.yanzhenjie.recyclerview.OnItemMenuClickListener
import com.yanzhenjie.recyclerview.SwipeMenuCreator
import com.yanzhenjie.recyclerview.SwipeMenuItem
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2023/7/8 10:19
 * @Describe    : 我的收藏
 */
class FragmentCollectGoodsList : BaseFragment<MallViewModel, FragmentCollectGoodsListBinding>() {

    private var goodId: Int = 0
    private val mAdapter: CollectGoodsListAdapter by lazy { CollectGoodsListAdapter(arrayListOf()) }
    private lateinit var loadsir: LoadService<Any>
    private var adapterPosition = -1
    private var skuList: ArrayList<GoodsSkuResponse.ListBean> = arrayListOf()
    private var specId = -1
    private var buyCount = 1

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.tvWhiteTitle.text = "我的收藏"
        mDatabind.niceSpinner.isVisible = false
//        mDatabind.includeBar.toolbar.initClose("我的收藏") {
//            nav().navigateUp()
//        }

        mDatabind.niceSpinner.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_fe4542))
        mDatabind.niceSpinner.setTextColor(ContextCompat.getColor(requireContext(), R.color.white))
        mDatabind.niceSpinner.textSize = 18F
        mDatabind.niceSpinner.text = "店铺"
        mDatabind.niceSpinner.attachDataSource(listOf("商品", "店铺"))

        mDatabind.niceSpinner.setOnSpinnerItemSelectedListener { parent, _, position, _ ->
            val itemName = parent.getItemAtPosition(position).toString()
            mDatabind.niceSpinner.text = itemName
            when (itemName) {
                "商品" -> {

                }

                "店铺" -> {

                }
            }
        }

        val swipeMenuCreator = SwipeMenuCreator { _, rightMenu, _ ->
            val width = resources.getDimensionPixelSize(R.dimen.dp_70)
            val height = ViewGroup.LayoutParams.MATCH_PARENT
            val deleteItem = SwipeMenuItem(activity)
                .setBackgroundColor(Color.parseColor("#F44336"))
                .setTextColor(Color.WHITE)
                .setText("取消收藏")
                .setTextSize(15)
                .setWidth(width)
                .setHeight(height)
            rightMenu.addMenuItem(deleteItem)
        }
        mDatabind.layoutList.swipeRecyclerView.setSwipeMenuCreator(swipeMenuCreator)

        val mItemMenuClickListener = OnItemMenuClickListener { menuBridge, position ->
            /** 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱 */
            menuBridge.closeMenu()
            /** 调用删除接口 */
            cancelCollect(mAdapter.data[position].id)
        }
        mDatabind.layoutList.swipeRecyclerView.setOnItemMenuClickListener(mItemMenuClickListener)

        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, Util.dp2px(context, 10f)))
            it.initFooter {
                //触发加载更多时请求数据
                mViewModel.getCollectGoodList(false)
            }
        }
        //状态页配置
        loadsir = loadServiceInit(mDatabind.layoutList.swipeRefreshLayout) {
            //点击重试时触发的操作
            onRefresh()
        }
        mDatabind.layoutList.swipeRefreshLayout.init {
            onRefresh()
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            nav().navigateAction(R.id.action_to_fragment_goods_detail, Bundle().apply {
                putString("id", mAdapter.data[position].goodId.toString())
            })
        }

        mAdapter.addChildClickViewIds(R.id.ivItemCollectGoodAddCar, R.id.llShopName)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.ivItemCollectGoodAddCar -> {
                    adapterPosition = position
                    goodId = mAdapter.data[position].goodId
                    showLoadingAntiShake(getString(R.string.loading))
                    mViewModel.getGoodSkuList(goodId.toString())
                }

                R.id.llShopName -> {
                    nav().navigateAction(R.id.action_to_fragment_merchant_store, Bundle().apply {
                        putInt("shopId", mAdapter.data[position].shopId)
                    })
                }
            }
        }
    }

    private fun cancelCollect(id: Int) {
        showLoading(getString(R.string.loading))
        val body = CancelCollectParam(id = id)
        mViewModel.deleteCollectGood(body)
    }

    override fun onResume() {
        super.onResume()
        onRefresh()
    }

    private fun onRefresh() {
        loadsir.showLoading()
        mViewModel.getCollectGoodList(true)
    }

    override fun createObserver() {
        super.createObserver()
        /** 获取商品sku列表 */
        mViewModel.goodsSkuResult.observe(viewLifecycleOwner) {
            dismissLoadingAntiShake()
            if (it?.list == null || it.list.size == 0) {
                return@observe
            }
            skuList = it.list
            showBottomDialogAddCar(it)
        }
        /** 删除收藏 */
        mViewModel.delCollectResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                onRefresh()
            }
        }
        /** 获取收藏列表 */
        mViewModel.collectGoodsResult.observe(viewLifecycleOwner) {
            loadListData(it, mAdapter, loadsir, mDatabind.layoutList.swipeRecyclerView, mDatabind.layoutList.swipeRefreshLayout)
        }
        /** 添加到购物车  */
        mViewModel.addShoppingCarResult.observe(viewLifecycleOwner) {
            eventViewModel.addShopCarResult.value = true
            RxToast.showToast("已添加")
            if (dialogBottom.isShowing)
                dialogBottom.dismiss()
        }
    }

    private lateinit var dialogBottom: BottomSheetDialog
    private lateinit var btnSubmit: Button
    private lateinit var buySkuNoLl: LinearLayout
    private lateinit var buySkuAdd: AppCompatTextView
    private lateinit var buySkuRe: AppCompatTextView
    private lateinit var ibSkuClose: ImageView
    private lateinit var buySkuNo: TextView
    private lateinit var tvSkuSellingPrice: TextView
    private lateinit var tvSkuSellingPriceUnit: TextView
    private lateinit var tvSkuInfo: TextView
    private lateinit var llCoupon: LinearLayout
    private var ivSkuLogo: ImageView? = null
    var checkPosition = -1

    @SuppressLint("SetTextI18n")
    private fun showBottomDialogAddCar(it: GoodsSkuResponse) {
        dialogBottom = context?.let { BottomSheetDialog(it, R.style.BottomSheetDialog) }!!
        val dialogView: View = LayoutInflater.from(context).inflate(R.layout.bottom_sku_dialog, null)
        tvSkuSellingPrice = dialogView.findViewById(R.id.tv_sku_selling_price)
        tvSkuSellingPriceUnit = dialogView.findViewById(R.id.tv_sku_selling_price_unit)
        tvSkuInfo = dialogView.findViewById(R.id.tv_sku_info)
        buySkuNo = dialogView.findViewById(R.id.buy_sku_no)
        buySkuAdd = dialogView.findViewById(R.id.buy_sku_add)
        buySkuRe = dialogView.findViewById(R.id.buy_sku_re)
        btnSubmit = dialogView.findViewById(R.id.btn_submit)
        buySkuNoLl = dialogView.findViewById(R.id.buy_sku_no_ll)
        ibSkuClose = dialogView.findViewById(R.id.ib_sku_close)
        ivSkuLogo = dialogView.findViewById(R.id.iv_sku_logo)
        val tvGoodsName = dialogView.findViewById<TextView>(R.id.tv_goods_name)
        llCoupon = dialogView.findViewById(R.id.llCoupon)
        val marketShopMainSkuList = dialogView.findViewById<TagFlowLayout>(R.id.market_shop_main_sku_list)

        ImageLoaderManager.loadRoundImageOrEmpty(context, mAdapter.data[adapterPosition].goodImg, ivSkuLogo, 15, R.drawable.shop_product_def)
        if (checkPosition != -1) {
            tvSkuSellingPrice.text = "¥ " + it.list[checkPosition].salePrice.toString()
            tvSkuSellingPriceUnit.text = "库存:" + it.list[checkPosition].inventory.toString()
            tvSkuInfo.text = getString(R.string.yixuan) + it.list[checkPosition].specName
        }
        tvGoodsName.text = mAdapter.data[adapterPosition].goodName
        llCoupon.visibility = View.GONE
        setSkuAdapterData(marketShopMainSkuList, it)
        if (checkPosition == -1) {
            onUnChecked()
        } else {
            (marketShopMainSkuList.adapter as TagAdapter<*>).setSelectedList(checkPosition)
        }
        ibSkuClose.setOnClickListener {
            if (::dialogBottom.isInitialized && dialogBottom.isShowing) {
                dialogBottom.dismiss()
            }
        }
        dialogBottom.setContentView(dialogView)
        dialogBottom.show()
    }

    private fun setSkuAdapterData(marketShopMainSkuList: TagFlowLayout?, goodsSkuResult: GoodsSkuResponse) {
        val tagAdapter = object : TagAdapter<GoodsSkuResponse.ListBean>(skuList) {
            override fun getView(parent: FlowLayout?, position: Int, skuItemBean: GoodsSkuResponse.ListBean): View {
                val tv = layoutInflater.inflate(R.layout.sku_tv, parent, false) as TextView
                tv.text = skuItemBean.specName
                return tv
            }

            @SuppressLint("SetTextI18n")
            override fun onSelected(position: Int, view: View?) {
                super.onSelected(position, view)
                checkPosition = position
                specId = goodsSkuResult.list[position].id
                onChecked(skuList[position])
                ImageLoaderManager.loadRoundImageOrEmpty(context, skuList[position].specImgPath, ivSkuLogo, 5, R.drawable.shop_product_def)
            }

            override fun unSelected(position: Int, view: View?) {
                super.unSelected(position, view)
                checkPosition = -1
                onUnChecked()
            }
        }
        if (checkPosition != -1) {
            tagAdapter.setSelectedList(checkPosition)//默认选中的标签位置
        }
        if (marketShopMainSkuList != null) {
            marketShopMainSkuList.adapter = tagAdapter
        }
    }

    private fun onUnChecked() {
        tvSkuSellingPrice.text = "¥0.0"
        tvSkuSellingPriceUnit.text = "库存:0"
        tvSkuInfo.text = getString(R.string.qingxuanze)
        btnSubmit.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_8F8F8F))
        btnSubmit.text = getString(R.string.market_shop_product_detail_sku_activity_dialog_please_select_sku)
        buySkuNoLl.visibility = View.INVISIBLE
        btnSubmit.isClickable = false
        buySkuAdd.isClickable = false
        buySkuRe.isClickable = false
    }

    @SuppressLint("SetTextI18n")
    private fun onChecked(listBean: GoodsSkuResponse.ListBean) {
        tvSkuSellingPrice.text = "¥" + listBean.salePrice.toString()
        tvSkuSellingPriceUnit.text = "库存:" + listBean.inventory.toString()
        tvSkuInfo.text = getString(R.string.yixuan) + listBean.specName
        btnSubmit.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_fe4542))
        btnSubmit.text = getString(R.string.market_shop_product_detail_sku_activity_dialog_add_shop_car)
        buySkuNoLl.visibility = View.VISIBLE
        btnSubmit.isClickable = true
        buySkuAdd.isClickable = true
        buySkuRe.isClickable = true
        if (buySkuNo.text.toString().toInt() > listBean.inventory) {
            buySkuNo.text = "" + listBean.inventory
        }
        buySkuAdd.setOnClickListener {
            val skuNoNow = buySkuNo.text.toString().toInt()
            if (skuNoNow < 2) {
                return@setOnClickListener
            } else {
                buySkuNo.text = "" + (skuNoNow - 1)
            }
        }
        buySkuRe.setOnClickListener {
            val skuNoNow = buySkuNo.text.toString().toInt()
            if (skuNoNow >= listBean.inventory) {
                RxToast.showToast("商品数量不可大于库存")
                return@setOnClickListener
            } else {
                buySkuNo.text = "" + (skuNoNow + 1)
            }
        }

        btnSubmit.setOnClickListener {
            buyCount = buySkuNo.text.toString().toInt()
            if (buyCount < 1) {
                RxToast.showToast(getString(R.string.MarketShopProductDetailSkuActivityDialogBuyCountLowerThanZero))
                return@setOnClickListener
            }
            showLoading(getString(R.string.loading))
            val body = AddShoppingCarParam(goodId, specId, buyCount)
            mViewModel.addToShopCart(body)
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.ivBack) {
            nav().navigateUp()
        }
    }
}